<?php

namespace plugin\laoha\app\controller;

use plugin\laoha\app\model\Post;
use plugin\admin\app\model\User;
use plugin\laoha\api\Captcha;
use plugin\laoha\api\Limit;
use Webman\Event\Event;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class UserController extends Crud
{
    protected $noNeedLogin = ['index', 'list', 'select', 'show','login','collect','comment'];
    protected $user_id;
    protected $url;


    public function __construct()
    {
        $this->model = new User;
        $this->rules = $this->getRules();
        $this->user_id = request()->get('user_id',0) ?: user_id(); 
        $this->url = request()->fullUrl();
    }

    public function index(Request $request){
        $model = new User;
        $user = $model->find($this->user_id);
        if(!$user){
            return $this->out('未找到用户');
        }
        $params = [
            'data'=>$user->toArray(),
            'user_id'=>$this->user_id,
            'url'=>$this->url,
            'title'=>'用户首页',
            'bread' => '用户首页',
        ];
        return $this->out($params, 'user/index');
    }

    public function collect(Request $request){
        $model = new Post;
        $user_id = $this->user_id;
        $builder = $model->whereHas('acts',function($query) use($user_id){
            $query->where('act','collect')->where('user_id',$user_id);
        })->where('status',0);
        $set = ['page_type'=>1];
        $data = laoha_query($builder,$set,$model);
        $params = [
            'data'=>$data,
            'user_id'=>$this->user_id,
            'url'=>$this->url,
            'title'=>'文章收藏',
            'bread' => ['用户|/app/laoha/user/index', '文章收藏'],
        ];
        return $this->out($params, 'user/collect');
    }

    public function comment(Request $request){
        $model = new Post;
        $user_id = $this->user_id;
        $builder = $model->whereHas('comments',function($query) use($user_id){
            $query->where('user_id',$user_id);
        })->where('status',0)->with(['comments'=>function($query){
            $query->orderBy('id','desc');
        }]);
        $set = ['page_type'=>1];
        $data = laoha_query($builder,$set,$model);
        $params = [
            'data'=>$data,
            'user_id'=>$this->user_id,
            'url'=>$this->url,
            'title'=>'文章评论',
            'bread' => ['用户|/app/laoha/user/index', '文章评论'],
        ];
        return $this->out($params, 'user/comment');
    }

    //快速登录
    public function login(Request $request){
        if ($request->method() === 'POST') {

            // 每个ip每分钟只能调用10次
            Limit::perMinute($request->getRealIp(), 10);

            $username = $request->post('username');
            $password = $request->post('password');
            $imageCode = $request->post('image_code');

            $captchaData = session('captcha-image-login');

            try {
                Captcha::verify(null, $imageCode, $captchaData);
            } catch (BusinessException $exception) {
                return json(['code' => 1, 'msg' => '图形验证码错误', 'data' => [
                    'field' => 'image_code'
                ]]);
            }

            $request->session()->delete('captcha-image-register');

            $users = User::where('username', $username)
                ->orWhere('email', $username)
                ->orWhere('mobile', $username)
                ->get();

            foreach ($users as $user) {
                if (password_verify($password, $user->password)) {
                    if ($user->status != 0) {
                        return json(['code' => 1, 'msg' => '当前账户已经被禁用']);
                    }
                    $request->session()->set('user', [
                        'id' => $user->id,
                        'username' => $user->username,
                        'nickname' => $user->nickname,
                        'avatar' => $user->avatar,
                        'email' => $user->email,
                        'mobile' => $user->mobile,
                    ]);
                    // 发布登录事件
                    Event::emit('user.login', $user);
                    return json(['code' => 0, 'msg' => 'ok']);
                }
            }

            return json(['code' => 1, 'msg' => '用户名或密码错误']);
        }

        return view('user/login');
    }    

    /**
     * 退出
     * @param Request $request
     * @return Response
     */
    public function logout(Request $request): Response
    {
        $session = $request->session();
        $userId = session('user.id');
        if ($userId && $user = User::find($userId)) {
            // 发布退出事件
            Event::emit('user.logout', $user);
        }
        $session->delete('user');
        return json_ok('用户已成功退出');
    }    
}
